package com.molyfun.parents.im;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

import com.molyfun.parents.R;
import com.molyfun.parents.utils.BadgeUtil;
import com.tencent.imsdk.TIMOfflinePushListener;
import com.tencent.imsdk.TIMOfflinePushNotification;

import mabeijianxi.camera.util.Log;

/**
 * Created by ligang on 2018/1/16 0016.
 */

public class MyIMOfflinePushListener implements TIMOfflinePushListener {

    private final Intent msgIntent;
    private final NotificationManager notificationManager;
    private Context appContext;

    protected static int notifyID = 0525; // start notification id
    protected int notificationNum = 0;

    public MyIMOfflinePushListener(Context context) {
        this.appContext = context;
        notifyID = 0525;
        notificationNum = 0;
        notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        msgIntent = appContext.getPackageManager().getLaunchIntentForPackage(appContext.getApplicationInfo().packageName);
    }

    @Override
    public void handleNotification(TIMOfflinePushNotification timOfflinePushNotification) {
        Log.d("loginTIM", timOfflinePushNotification.getTitle() + "\n"
                + timOfflinePushNotification.getContent() + "\n"
                + timOfflinePushNotification.getConversationId() + "\n"
                + timOfflinePushNotification.getGroupName() + "\n"
                + timOfflinePushNotification.getSenderIdentifier() + "\n"
                + timOfflinePushNotification.getConversationType());
        NotificationCompat.Builder builder = new NotificationCompat.Builder(appContext)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setWhen(System.currentTimeMillis())
                .setAutoCancel(true);
        notifyID++;
        notificationNum++;
        PendingIntent pendingIntent = PendingIntent.getActivity(appContext, notifyID, msgIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentTitle(timOfflinePushNotification.getTitle());
        builder.setTicker("你有新消息");
        String content = timOfflinePushNotification.getContent();
        builder.setContentText(content.substring(content.indexOf(":") + 2));
        builder.setContentIntent(pendingIntent);
        builder.setNumber(notificationNum);
        Notification notification = builder.build();
        notification.defaults |= Notification.DEFAULT_ALL;
        notification.flags |= Notification.FLAG_AUTO_CANCEL;// 点击消息后,该消息自动退出
        notificationManager.notify(notifyID, notification);
        BadgeUtil.setBadgeCount(appContext, notificationNum, R.mipmap.ic_launcher);
    }
}
